package cmd

import (
	"encoding/json"
	"fmt"
	"gitee.com/cdsailyj/go-vpn/common/tool"
	"gitee.com/cdsailyj/go-vpn/common/util"
	"gitee.com/cdsailyj/go-vpn/global"
	"gitee.com/cdsailyj/go-vpn/service"
	"os"
	"reflect"
	"strings"
	"time"
)

//import (
//	"fmt"
//	"github.com/otiai10/gosseract/v2"
//)

type TestCmd struct{}

// 图片识别 ocr
func (t *TestCmd) Func1() {
	form := map[string]string{
		"applicationOfficeName": "新疆油田公司-采油一厂-稠油作业区",
	}
	//data, status, err := tool.HttpPostMultipart("http://localhost:18082/0/api/sys/offices/findIdByName", nil, nil, form, nil)

	headers := map[string]string{
		"authorization": "Bearer 65008397-cb4c-4b9a-ac15-1601dea8d385",
		"satoken":       "126a9910-0310-427f-bdd5-752fd4e2d24f",
	}
	data, status, err := tool.HttpPostMultipart(global.CONFIG.XjytGateway+"/aygc-service-sys/0/api/sys/offices/findIdByName", nil, nil, form, headers)

	fmt.Printf("%#v \t %#v \t %#v \n", string(data), status, err)

	//files := []string{"D:\\download\\img\\history\\1.jpg", "D:\\download\\img\\history\\3.jpg"}
	//others := map[string]string{}
	//resp, status, err := tool.HttpPostMultipart("http://127.0.0.1:8892/admin/upload", files, others, nil)
	//fmt.Println(string(resp), status, err)

	//client := gosseract.NewClient()
	//defer client.Close()
	//client.SetLanguage("chi_sim", "eng")
	//client.SetImage("/app/www/jt.png")
	//text, err := client.Text()
	//fmt.Printf("text:%#v|%#v\n", text, err)
}

type FaceDeleteResp struct {
	ErrorCode int         `json:"error_code"`
	ErrorMsg  string      `json:"error_msg"`
	LogId     int         `json:"log_id"`
	Timestamp int         `json:"timestamp"`
	Cached    int         `json:"cached"`
	Result    interface{} `json:"result"`
}

type FaceListResp struct {
	ErrorCode int    `json:"error_code"`
	ErrorMsg  string `json:"error_msg"`
	LogId     int64  `json:"log_id"`
	Timestamp int    `json:"timestamp"`
	Cached    int    `json:"cached"`
	Result    struct {
		UserIdList []string `json:"user_id_list"`
	} `json:"result"`
}

// 删除所有人脸数据
func (t *TestCmd) DeleteFace() {
	myFunc := func(i any) {
		deleteBytes, _, _ := tool.HttpPostJson("http://10.72.199.210:8300/face-api/v3/user/delete?appid=28129347", map[string]any{"group_id": "jy", "user_id": i}, nil)
		var faceDelete FaceDeleteResp
		json.Unmarshal(deleteBytes, &faceDelete)
		fmt.Printf("删除结果: %#v \n", faceDelete)
	}

	task := &util.AsyncTask{ChanLen: 100, TaskNum: 20}
	task.Start(myFunc)

	failTimes := 0
	for {
		bytes, status, err := tool.HttpPostJson("http://10.72.199.210:8300/face-api/v3/user/list?appid=28129347", map[string]any{"group_id": "jy", "start": 0, "length": 1000}, nil)
		var faceList FaceListResp
		err = json.Unmarshal(bytes, &faceList)
		fmt.Printf("查询列表数据：%#v \t %#v \t %#v \n", faceList, status, err)
		if faceList.ErrorCode != 0 || len(faceList.Result.UserIdList) == 0 {
			failTimes++
			if failTimes > 10 {
				break
			}
			time.Sleep(2 * time.Second)
			continue
		}
		// 2. 将数据分发到jobs通道
		for _, num := range faceList.Result.UserIdList {
			task.Chan <- num
		}
	}

	task.Stop()
}

func (t *TestCmd) getImageType(filename string) string {
	if len(filename) == 0 {
		return "png"
	}
	arr := strings.Split(filename, ".")
	typeVal := strings.ToLower(arr[len(arr)-1])
	if typeVal == "jpg" {
		typeVal = "jpeg"
	}
	return typeVal
}

var faceService = new(service.FaceService)

func (t *TestCmd) AddFace() {
	faceUrl := "http://10.72.199.210:9005/algorithm-spfx-new/data/5ba34926f8279df4fe178731af4d94995e90e8a14f434706a152a70b78616276.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20250327%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250327T044135Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=52ea5ef1ac60de7049c6aa4f25be35f43bed173316d5514ad78be38d58a23e9e"
	man := service.ManFaceInfoDto{
		ManNumber:   "340828199007104814",
		IdCard:      "340828199007104814",
		TenantName:  "嘉洋",
		PhoneNumber: "17302185530",
		Sex:         "男",
		ManName:     "储德盛",
		ImageUrl:    faceUrl,
	}
	err := faceService.SyncFaceInfo(man.ImageUrl, man.IdCard, "", man.ManName, man.PhoneNumber, man.TenantName)
	fmt.Printf("%#v \n", err)
}

func (t *TestCmd) UploadImage() {
	bytes, err := os.ReadFile("E:\\文件\\档案\\small-600.jpg")
	faceUrl, err := faceService.UploadImg(bytes, "uploadFile", "small-600.jpg")
	fmt.Printf("%#v   \t  %#v", faceUrl, err)
}

func (t *TestCmd) Identity() {
	bytes, err := os.ReadFile("E:\\文件\\档案\\small-600.jpg")

	faceList, err := faceService.FaceIdentify(tool.Base64Encode(bytes))
	fmt.Printf("%#v   \t  %#v", faceList, err)
}

func (t *TestCmd) SearchFace() {
	faceList, err := faceService.GetFaceByIdCard("340828199007104814")
	fmt.Printf("%#v   \t  %#v", faceList, err)
}

func (t *TestCmd) Download() {
	fmt.Printf("%#v  %#v   %#v\n", os.Getenv("GO_HTTP_PROXY"))
	imageByte, status, err := tool.HttpGet("https://zyothers.xuezhizhou.com.cn/xpzxothers/uphoto/1678025427815.jpg", nil, nil)
	fmt.Printf("%#v   \t%#v   \t  %#v", len(imageByte), status, err)
}

func (t *TestCmd) SyncFace() {
	myFunc := func(a any) {
		flag := false

		f, _ := a.(service.OutCert)
		//如果失败更新 = 3
		defer func() {
			if !flag {
				faceService.SetFail(f.ID)
			}
		}()

		if len(f.IDCODE) == 0 || strings.Contains(f.IDCODE, "*") {
			fmt.Printf("身份证错误 %s \n", f.IDCODE)
			return
		}

		//查重
		rows, err := faceService.GetFaceByIdCard(f.IDCODE)
		if rows != nil && len(rows) > 0 {
			faceService.SetSuccess(f.ID)
			flag = true
			return
		}

		originalFaceUrl := strings.ReplaceAll(f.PORTAIT, "https://xpzx.xjxpzx.com.cn:8098/", "http://zyothers.xuezhizhou.com.cn/")
		fmt.Printf("人脸图片URL------------------ %s \n", originalFaceUrl)
		imageByte, status, err := tool.HttpGet(originalFaceUrl, nil, nil)
		if err != nil || status != 200 {
			fmt.Printf("图片下载错误 \t %s %#v \n", originalFaceUrl, status)
			return
		}

		if len(imageByte) < 200 {
			fmt.Printf("图片不合格 %s \n", originalFaceUrl)
			return
		}

		faceUrl, err := faceService.UploadImg(imageByte, "uploadFile", fmt.Sprintf("%s.%s", f.ID, t.getImageType(originalFaceUrl)))
		if err != nil || len(faceUrl) == 0 {
			fmt.Printf("图片上传错误 %#v \n", err)
			return
		}

		err = faceService.SyncFaceInfo(faceUrl, f.IDCODE, f.USER_ID, f.USER_NAME, "11111111111", f.OFFICE_NAME)
		if err != nil {
			fmt.Printf("人脸同步失败: %v \t %v \n", f.ID, err.Error())
			return
		}
		_, err = faceService.SetSuccess(f.ID)
		if err != nil {
			fmt.Printf("修改 IS_HANDLE_PHOTO 错误 %s \n", err.Error())
			return
		}

		flag = true
		fmt.Printf("SUCCESS!!!!!!!!!!!!!!! %v \n", f.ID)
	}

	task := &util.AsyncTask{ChanLen: 100, TaskNum: 10}
	task.Start(myFunc)

	failTimes := 0
	for {
		results, err := faceService.GetFaceData()
		if err != nil || len(results) == 0 {
			failTimes++
			fmt.Printf("---------------查询失败:%#v---------------\n", err)
			if failTimes > 10 {
				break
			}
			continue
		}
		fmt.Printf("数据总量：%#v \n", len(results))

		for _, f := range results {
			task.Chan <- f
		}
	}

	task.Stop()
}

func (t *TestCmd) SyncId() {
	list, err := faceService.GetSignData()
	if err != nil {
		fmt.Printf("列表为空 %#v\n", err)
	}
	fmt.Printf("列表数据 %#v\n", list)
}

type Token struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int    `json:"expires_in"`
}

// /oauth/oauth/token  grant_type: password  username: jy-wjb  password :JY5tgb6yhn7ujm8ik,  client_id: aygc  client_secret: Anyangch@123
func GetToken() (string, error) {
	//公钥  MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJL0JkqsUoK6kt3JyogsgqNp9VDGDp+t3ZAGMbVoMPdHNT2nfiIVh9ZMNHF7g2XiAa8O8AQWyh2PjMR0NiUSVQMCAwEAAQ==
	// cus2p88wdA9u6mHILCTignAj5SPUci882WxxGcPV53Mi0nSsi/0uWhueRgGA82boCphe7fOD7+o4Lr1Fdi0IHQ==
	// Yt1ekAx4zSpHl+EPJ4bCk2fCdeOYlhdMb1/BJgo0yJ3PG6Y7KvMmjypSlLO5Xc3+nA6BOrBuVwqMfTqOFZKhqA==

	passWd, err := tool.RSAEncryptPKCS1v15([]byte("-----BEGIN PUBLIC KEY-----\n"+global.CONFIG.PubKey+"\n-----END PUBLIC KEY-----"), []byte("1qaz@WSX#EDC1"))
	if err != nil {
		fmt.Printf("EncryptPKCS1v15错误: %#v\n", err)
	}

	baseByte := tool.Base64Encode(passWd)
	form := map[string]string{
		"grant_type":    "password",
		"username":      "jy-wjb",
		"password":      baseByte,
		"client_id":     "aygc",
		"client_secret": "Anyangch@123",
	}
	resp, status, err := tool.HttpPostMultipart(global.CONFIG.XjytGateway+"/oauth/oauth/token", nil, nil, form, nil)
	fmt.Printf("HttpPostMultipart: %#v \t %#v \t %#v\n", string(resp), status, err)
	var data Token
	err = json.Unmarshal(resp, &data)
	if err != nil {
		return "", err
	}
	return data.AccessToken, nil
}

func (t *TestCmd) Secret() {
	GetToken()
}

func (t *TestCmd) Refresh() {
	form := map[string]string{
		"grant_type":    "refresh_token",
		"refresh_token": "18883716-cdbe-48f2-893f-726a17c238a6",
		"client_id":     "aygc",
		"client_secret": "Anyangch@123",
	}
	resp, status, err := tool.HttpPostMultipart(global.CONFIG.XjytGateway+"/oauth/oauth/token", nil, nil, form, nil)
	fmt.Printf("HttpPostMultipart: %#v \t %#v \t %#v\n", string(resp), status, err)
}

func (t *TestCmd) Ref() {
	a := 1
	ap := &a

	var c tool.ExcelSheetHeader
	cr := reflect.ValueOf(c)

	v1 := reflect.ValueOf(a)
	v := reflect.ValueOf(ap)
	fmt.Printf("%#v \n", v1.Type().Kind() == reflect.Ptr)
	fmt.Printf("%#v \n", v.Type().Kind() == reflect.Ptr)

	fmt.Printf("%#v \n", v.Kind())
	fmt.Printf("%#v \n", v1.Kind())

	fmt.Printf("%#v \n", v1.Int())
	fmt.Printf("%#v \n", v.Elem().Int())

	fmt.Printf("%#v \n", cr.Kind() == reflect.Struct)
	fmt.Printf("%#v \n", cr.Type().PkgPath())

}
